# V交流：by15188607997
# 双低转债
# -*- coding:utf-8 -*-
import csv
import re
import time
from operator import itemgetter

import requests
from lxml import etree

from kzz.GetLoginData import get_jsl_data


def get_dat():
    dat = get_jsl_data()
    print(dat)

    # 所有数据
    lst_data = []
    for one in dat['rows']:
        # 每一条数据
        lst_dat = []
        # 转债id
        id = one["id"]
        dat_cell = one["cell"]
        # 是否赎回
        is_shui = dat_cell['force_redeem']
        if is_shui == None:
            # 转债名称
            name = dat_cell['bond_nm']
            # 现价
            price = dat_cell['price']
            # 溢价率
            premium_rt = dat_cell['premium_rt']
            # 评级
            rating_cd = dat_cell['rating_cd']
            # 回售触发价
            put_convert_price = dat_cell['put_convert_price']
            # 强赎触发价
            force_redeem_price = dat_cell['force_redeem_price']
            # 剩余时间
            last_time = dat_cell['year_left']
            # 剩余规模
            last_scale = dat_cell['orig_iss_amt']
            # 到期税前收益
            ytm_rt = dat_cell['ytm_rt']
            # 双低
            dblow = dat_cell['dblow']
            # 评分
            print("------------>" + ytm_rt.strip("%"))
            if premium_rt != '-' and ytm_rt != '-':
                score = round(float(premium_rt.strip("%")), 2) + float(price) - round(float(ytm_rt.strip("%")), 2)
            else:
                score = 1000

            # 获取赎回价
            xiangqing_url = 'https://www.jisilu.cn/data/convert_bond_detail/' + id
            xiangqing_response = requests.get(xiangqing_url)
            html = xiangqing_response.content.decode("utf-8")
            html = etree.HTML(html)
            lixi = html.xpath('.//td[@id="cpn_desc"]/text()')
            pattern = re.compile(r'\d+\.\d+?')  # 查找数字
            lixi = pattern.findall(lixi[0])
            shuhuijia = html.xpath('.//td[@id="redeem_price"]/text()')
            li_price = 0
            for li in lixi:
                li_price = li_price + float(li)
            try:
                jiancang = float(shuhuijia[0]) + (li_price - float(lixi[-1])) * 0.8
            except:
                jiancang = 0

            # 是否可操作
            if jiancang != 0 and float(price) - jiancang < 3:
                is_oper = '建仓'
                if jiancang != 0 and float(price) - float(shuhuijia[0]) < 3:
                    is_oper = '加仓'
            else:
                is_oper = ''
            lst_dat.append(score)
            lst_dat.append(id)
            lst_dat.append(name)
            lst_dat.append(price)
            lst_dat.append(jiancang)
            lst_dat.append(shuhuijia[0])
            lst_dat.append('')
            lst_dat.append(premium_rt)
            lst_dat.append(rating_cd)
            lst_dat.append(put_convert_price)
            lst_dat.append(force_redeem_price)
            lst_dat.append(last_time)
            lst_dat.append(last_scale)
            lst_dat.append(ytm_rt)
            lst_dat.append(dblow)
            lst_dat.append(is_oper)
            lst_data.append(lst_dat)
        else:
            continue

    lst_data = sorted(lst_data, key=itemgetter(0), reverse=False)
    return lst_data


def write_csv(data):
    # 格式化成2016-03-20形式
    today = time.strftime("%Y-%m-%d", time.localtime())
    print(today + '_____________________')
    # 1. 创建文件对象
    f = open('可转债' + today + '.csv', 'w', encoding='utf-8', newline='')
    # 2. 基于文件对象构建 csv写入对象
    csv_writer = csv.writer(f)
    # 3. 构建列表头
    csv_writer.writerow(["评分", "代 码", "转债名称", "现 价", "建仓线", "加仓线", "重仓线", "溢价率", "评级",
                         "回售触发价", "强赎触发价", "剩余年限", "剩余规模", "到期税前收益", "双低", "操作"])
    # 4. 写入csv文件内容
    for dat in data:
        csv_writer.writerow(dat)
    # 5. 关闭文件
    f.close()


if __name__ == '__main__':
    data = get_dat()
    write_csv(data)
